const Task = require('../models/task')
const User = require('../models/user')
const Category = require('../models/category')
const Taskaudit = require('../models/taskaudit')

const response = require('../utils/response')
const loop = require('../utils/loop')
const {huanTime} = require('../utils/tool')

const fs = require('fs')
let path = require('path')
const mongoose = require('mongoose')


// 提交的审核任务列表
exports.submitForReview = async (req, res, next) => {
  try {
    var limitNumber = Number(req.query.limitNumber) || Number(5)
    var skipNumber = Number(req.query.skipNumber) || Number(0)
    const userId = req.query.userId
    const status = req.query.status
    const task = await Task.find({
        status: status,
        worker: userId
      })
      .populate('worker', ['name'])
      .populate('creator', ['name'])
      .populate('parentId', ['taskname'])
      .sort({
        _id: -1
      })
      .skip(skipNumber) //跳过前sortNumber文档
      .limit(limitNumber) //查询后面的limitNumber个文档
      .lean()

    response(res, 200, '成功', task)
  } catch (err) {
    next(err)
  }
}

// 审核别人的任务列表
exports.auditOthers = async (req, res, next) => {
  try {
    var limitNumber = Number(req.query.limitNumber) || Number(5)
    var skipNumber = Number(req.query.skipNumber) || Number(0)
    const userId = req.query.userId
    const status = req.query.status
    const task = await Task.find({
        status: status,
        creator: userId
      })
      .populate('worker', ['name'])
      .populate('creator', ['name'])
      .populate('parentId', ['taskname'])
      .sort({
        _id: -1
      })
      .skip(skipNumber) //跳过前sortNumber文档
      .limit(limitNumber) //查询后面的limitNumber个文档
      .lean()

    response(res, 200, '成功', task)
  } catch (err) {
    next(err)
  }
}

//根据用户id获取审核列表
exports.auditList = async (req, res, next) => {
  try {
    const userId = req.params.userId
    let auditList = await Taskaudit.find({
      reviewer: userId,
      void: 0
    }).lean()

    if (auditList.length === 0) return response(res, 402, "该用户没有审核任务~~", null)

    response(res, 200, "获取审核列表成功", auditList)
  } catch (error) {
    next(error)
  }
}

//根据审核id获取一条审核数据
exports.auditOne = async (req, res, next) => {
  try {
    const auditId = req.params.auditId
    let model = await Taskaudit.findById(auditId).populate("taskId").populate("reviewer", ["name"]).lean()
    if (!model) return response(res, 402, "获取失败~~", null)

    //查询出负责人
    let workers = model.taskId.worker
    let worker = []
    for (let i in workers) {
      let user = await User.findById(workers[i])
      worker.push(user)
    }
    model.taskId.worker = worker

    // res.send(model)
    response(res, 200, "获取成功~~", model)
  } catch (error) {
    next(error)
  }
}

//通过审核
exports.adoptAudit = async (req, res, next) => {
  try {
    const fileId = req.params.fileId
    let audit = await Taskaudit.findOne({fileId}).lean()
    if (audit.status === 1) return response(res, 402, "该任务已通过，请勿重复操作~~", null)

    //修改审核表
    audit.status = 1
    audit.updatedAt = huanTime(Date.now())
    let model = await Taskaudit.findByIdAndUpdate(audit._id, audit)

    //修改任务表
    // let task = await Task.findById(audit.taskId).lean()
    // task.status = 3
    // let oldData = await Task.findByIdAndUpdate(task._id, task)
    // res.send(model)
    // req.oldData = oldData
    // req.newData = task
    // req.operate = 4
    // next()
    response(res, 200, "审核通过", audit)
  } catch (error) {
    next(error)
  }
}

//打回
exports.returnAudit = async (req, res, next) => {
  try {
    let audit = req.audit

    //修改审核表
    audit.status = 2
    // audit.void = 1
    audit.updatedAt = huanTime(Date.now())
    let model = await Taskaudit.findByIdAndUpdate(audit._id, audit)

    //修改任务
    let task = await Task.findById(audit.taskId).lean()
    for (let i in task.fileAddress){
      if (mongoose.Types.ObjectId(task.fileAddress[i]._id).toString() == mongoose.Types.ObjectId(audit.fileId).toString()) {
        task.fileAddress[i].void = false
      }
    }
    // task.status = 2
    // task.process = parseInt(task.process) - 10
    task.updatedAt = huanTime(Date.now())
    let oldData = await Task.findByIdAndUpdate(task._id, task)

    req.oldData = oldData
    req.newData = task
    req.operate = 5
    next()
    // response(res, 200, "打回成功", model)

  } catch (error) {
    next(error)
  }
}

//获取未读审核数量
exports.getUnread = async (req, res, next) => {
  const userId = req.params.userId
  let count = await Taskaudit.find({
    isRead: false,
    reviewer: userId,
    void: 0
  }).count()
  response(res, 200, "获取成功", {
    count
  })
}

//已读
exports.handleRead = async (req, res, next) => {
  const auditId = req.params.auditId

  let Audit = await Taskaudit.findById(auditId).lean()
  Audit.isRead = true
  Audit.updatedAt = huanTime(Date.now())
  await Taskaudit.findByIdAndUpdate(auditId, Audit)

  response(res, 200, "修改成功", Audit)
}